package com.github.hwangrq.minicat.server;

import com.github.hwangrq.minicat.utils.HttpProtocolUtil;
import com.github.hwangrq.minicat.utils.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author hwangrq
 * @date 2021/3/16 22:06
 * @description
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 使用输出流指定字符串
     * @param content String
     * @throws IOException IOException
     */
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    /**
     * 根据url获取静态资源绝对路径
     * 进一步根据绝对路径获取该静态资源文件
     * 最终通过输出流输出
     * @param path url
     */
    public void outputHtml(String path) throws IOException {
        // 静态资源绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);
        System.out.println(absoluteResourcePath);

        // 输入静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            //读取静态资源文件，输出静态资源
            FileInputStream inputStream = new FileInputStream(absoluteResourcePath);
            StaticResourceUtil.outputStaticResource(inputStream, outputStream);
        } else {
            // 404
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }
}
